class WebSocketClient {
    constructor(url, reconnectInterval = 3000, maxReconnect = 10) {
        this.url = url;
        this.ws = null;
        this.reconnectInterval = reconnectInterval; // 重新连接的时间间隔（毫秒） 
        this.maxReconnect = maxReconnect; // 最大重试次数 
        this.connect()
    }
    // websocket连接
    connect() {
        this.ws = new WebSocket(this.url);

        // websocket连接成功
        this.ws.open = () => {
        };
        // websocket消息
        this.ws.onmessage = event => {

        };
        // websocket关闭
        this.ws.onclose = event => {
            if (!event.wasClean) this.reconnect(); //异常连接尝试重新连接  
        };
        // websocket报错
        this.ws.onerror = error => {
            console.log("WebSocket发生错误：" + error);
        };
    }

    // 断开重连机制
    reconnect() {
        if (this.maxReconnect == 0) {
            console.log("已尝试重新连接次数过多，放弃连接");
            return;
        }
        console.log("尝试重新连接...");
        setTimeout(() => this.connect(), this.reconnectInterval); // 定时尝试重新连接  
        this.maxReconnect--; // 减少重试次数  
    }


}
export { WebSocketClient }
